package com.ruoyi.framework.config.mqtt;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Map;

/**
 * @description 消费监听, 接收mqtt消息并处理，控制分拣机
 */
@Component
@Slf4j
public class PushCallback implements MqttCallback {
    private static MqttClient mqttClient;
    @Value("${mqtt.host}")
    private String host;
    @Value("${mqtt.clientId}")
    private String clientId;
    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    @Value("${mqtt.timeout}")
    private int timeout;
    @Value("${mqtt.keepalive}")
    private int keepalive;
    public PushCallback() {
    }

    @Override
    public void connectionLost(Throwable throwable) {
        if (mqttClient == null || !mqttClient.isConnected()) {
            log.info("连接断开，正在重连....");
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        try {
            log.info("接收消息主题 : {}", topic);
            log.info("接收消息Qos : {}", message.getQos());
            String jsonPayload = new String(message.getPayload());
            log.info("接收消息内容 : {}", jsonPayload);
            if ("sea".equals(topic)) {
                // 创建一个 ObjectMapper 实例，用于将 JSON 字符串解析为 Java 对象
                ObjectMapper objectMapper = new ObjectMapper();
                // 使用 ObjectMapper 将接收到的 JSON 消息（jsonPayload）解析为一个 Map 对象
                Map<String, Object> jsonMap = objectMapper.readValue(jsonPayload, Map.class);
                String runValue = (String) jsonMap.get("run");
                log.info("解析后的 JSON 数据: {}", runValue);
            }
        } catch (Exception e) {
            log.error("接受消息错误: {}", e.getMessage());
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("deliveryComplete---------{}", token.isComplete());
    }
}